package online.westonline.com.westonline.ui;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;


import com.grandbroad.online.greendao.NodeBeanDao;


import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.adapter.NodeAdpter;
import online.westonline.com.westonline.adapter.NodeListAdpter;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.entry.NodeBean;
import online.westonline.com.westonline.utils.GreenDaoUtils;
import online.westonline.com.westonline.utils.UiUtlis;

/**
 * 笔记列表
 */
public class NodeActivity extends BaseActivity {
    private static final int MYLIVE_MODE_CHECK = 0;
    private static final int MYLIVE_MODE_EDIT = 1;
    private int mEditMode = MYLIVE_MODE_CHECK;
    private int mEditModeCard=MYLIVE_MODE_CHECK;
    private boolean isSelectAll = false;
    private boolean editorStatus = false;
    private boolean editorStatusCard = false;
    private int index = 0;
    private boolean showselectbarcard=false;
    private boolean showselectbar=false;

    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recycler_nodelist)
    RecyclerView recyclerNodelist;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.checkbox_all)
    CheckBox checkboxAll;
    @BindView(R.id.card_checkall)
    CardView cardCheckall;
    @BindView(R.id.tv_cancel)
    TextView tvCancel;
    @BindView(R.id.tv_node_delete)
    TextView tvNodeDelete;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.img_toolbar_menu)
    ImageView imgToolbarMenu;
    @BindView(R.id.recycler_nodelist_ver)
    RecyclerView recyclerNodelistVer;
    private boolean isSelectAllCard;
    private NodeBeanDao beanDao;
    private NodeAdpter node_adpter;
    private NodeListAdpter listAdpter;
    private List<NodeBean> datas = new LinkedList<>();
    private String type;

    @Override
    protected void initview() {
        //状态栏配置
        toolbar.setTitle("笔记");
        toolbar.setTitleTextColor(UiUtlis.getColor(R.color.BlueTheme));
        //默认为卡片流式布局
        imgToolbarMenu.setBackgroundResource(R.drawable.ic_view_headline_grey_500_24dp);
        tvTopbarTitleCenter.setText(type);
        tvTopbarTitleCenter.setTextColor(Color.BLACK);
        setSupportActionBar(toolbar);
        toolbar.setBackgroundColor(UiUtlis.getColor(R.color.colorAppTheme));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_keyboard_arrow_left_blue_500_24dp);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        initrecyclerview();
        initsession();
    }

    private void initrecyclerview() {
        listAdpter = new NodeListAdpter();
        recyclerNodelistVer.setLayoutManager(new LinearLayoutManager(this));
        recyclerNodelistVer.setAdapter(listAdpter);


        //同下
        configlistrecycler();
        node_adpter = new NodeAdpter();
        recyclerNodelist.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
        recyclerNodelist.setAdapter(node_adpter);
        //数据已经初始化了一遍所有......
        configrecycler();
    }

    private void configlistrecycler() {
        listAdpter.setDatas(datas);
        listAdpter.notifyDataSetChanged();
    }

    private void configrecycler() {
        node_adpter.setNodeBeans(datas);
        node_adpter.notifyDataSetChanged();
    }


    /**
     * 事件初始
     */
    private void initsession() {
        //切换视图
        imgToolbarMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recyclerNodelist.isShown())
                {
                    if (editorStatus)
                    {
                        editorStatus=false;
                    }
                    mEditMode = MYLIVE_MODE_EDIT;
                    updataEditMode();
                    showselectbar = false;
                    recyclerNodelist.setVisibility(View.GONE);
                    recyclerNodelistVer.setVisibility(View.VISIBLE);
                    //先移除
                    node_adpter.setNodeBeans(datas);
                    node_adpter.notifyDataSetChanged();
                    cardCheckall.setVisibility(View.GONE);
                    imgToolbarMenu.setBackgroundResource(R.drawable.ic_view_quilt_grey_500_24dp);

                }
                else
                {
                    if (editorStatusCard)
                    {
                        editorStatusCard=false;
                    }
                    updataEditModeByCard(MYLIVE_MODE_CHECK);
                    showselectbarcard = false;
                    recyclerNodelistVer.setVisibility(View.GONE);
                    recyclerNodelist.setVisibility(View.VISIBLE);
                    //移除所有视图
                    //重新查询
                    listAdpter.setDatas(datas);
                    listAdpter.notifyDataSetChanged();
                    cardCheckall.setVisibility(View.GONE);
                    imgToolbarMenu.setBackgroundResource(R.drawable.ic_view_headline_grey_500_24dp);
                }
            }
        });
        //卡片便签长按事件
        node_adpter.setLongClickListener(new NodeAdpter.onNodeLongClickListener() {
            @Override
            public void longClick(int pos, List<NodeBean> datas) {
                //弹出Checkbox
                //立即选中
                //标记开启
                if (!showselectbarcard)
                {
                    cardCheckall.setVisibility(View.VISIBLE);
                    showselectbarcard = true;
                    //设置adpter里的对应改变
                    updataEditModeByCard(MYLIVE_MODE_EDIT);
                }

            }
        });
        //卡片便签点击事件
        node_adpter.setClicklistener(new NodeAdpter.onNodeClicklistener() {
            @Override
            public void onClick(int pos, List<NodeBean> datas) {
                if (editorStatusCard) {
                    NodeBean myLive = datas.get(pos);
                    boolean isSelect = myLive.getCheck();
                    if (!isSelect) {
                        myLive.setCheck(true);
                        if (index == datas.size()) {
                            isSelectAllCard = true;
                        }
                    } else {
                        myLive.setCheck(false);
                        index--;
                        isSelectAllCard = false;
                    }
                    node_adpter.notifyItemChanged(pos,myLive);
                }
                else
                {
                    //通常情况下的点击
                    Bundle bundle = new Bundle();
                    //需要类型和便签的位置
                    bundle.putString("type",datas.get(pos).getType());
                    bundle.putInt("pos",pos);
                    startActivityWithBundle(NodeInfoActivity.class,false,bundle);
                }
            }
        });
        //列表便签长按事件
        listAdpter.setLongclicktoopen(new NodeListAdpter.longclicktoopen() {
            @Override
            public void open(int pos,  List<NodeBean> datas) {
                //打开下方选择
                if (!showselectbar)
                {
                    cardCheckall.setVisibility(View.VISIBLE);
                    showselectbar = true;
                    //设置adpter里的对应改变
                    updataEditMode();
                }

            }
        });
        //列表点击事件
        listAdpter.setClickto(new NodeListAdpter.clickto() {
            @Override
            public void click(int pos,  List<NodeBean> datas) {
                if (editorStatus) {
                    NodeBean myLive = datas.get(pos);
                    boolean isSelect = myLive.getCheck();
                    if (!isSelect) {
                        myLive.setCheck(true);
                        if (index == datas.size()) {
                            isSelectAll = true;
                        }
                    } else {
                        myLive.setCheck(false);
                        index--;
                        isSelectAll = false;
                    }
                    listAdpter.notifyItemChanged(pos,myLive);
                }
                else
                {
                    //通常情况下的点击
                    Bundle bundle = new Bundle();
                    //需要类型和便签的位置
                    bundle.putString("type",datas.get(pos).getType());
                    bundle.putInt("pos",pos);
                    startActivityWithBundle(NodeInfoActivity.class,false,bundle);
                }
            }
        });
        //全选事件
        checkboxAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recyclerNodelistVer.isShown())
                {
                    selectAllMain();
                }
                if (recyclerNodelist.isShown())
                {
                    selectAllMainbycard();
                }

            }
        });
        //下方删除点击事件
        tvNodeDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(NodeActivity.this);
                dialog.setCancelable(false);
                dialog.setTitle("提示");
                dialog.setMessage("删除后不可恢复,点击确定删除");
                dialog.setNegativeButton("取消",null);
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (recyclerNodelistVer.isShown())
                        {
                            for (int i = listAdpter.getDatas().size(), j =0 ; i > j; i--) {
                                NodeBean myLive = listAdpter.getDatas().get(i-1);
                                if (myLive.getCheck()) {
                                    listAdpter.getDatas().remove(myLive);
                                    //数据库移除
                                    beanDao.delete(myLive);
                                    datas.remove(myLive);
                                }
                            }
                            if (listAdpter.getDatas().size() == 0){
                                cardCheckall.setVisibility(View.GONE);
                            }
                            listAdpter.notifyDataSetChanged();
                        }
                        if (recyclerNodelist.isShown())
                        {
                            for (int i = node_adpter.getNodeBeans().size(), j =0 ; i > j; i--) {
                                NodeBean myLive = node_adpter.getNodeBeans().get(i-1);
                                if (myLive.getCheck()) {
                                    node_adpter.getNodeBeans().remove(myLive);
                                    //数据库移除
                                    beanDao.delete(myLive);
                                    datas.remove(myLive);
                                }
                            }
                            if (node_adpter.getNodeBeans().size() == 0){
                                cardCheckall.setVisibility(View.GONE);
                            }
                            node_adpter.notifyDataSetChanged();
                        }
                    }
                });
                dialog.show();
            }
        });
        //取消
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recyclerNodelistVer.isShown())
                {
                    //取消
                    updataEditMode();
                }
                if (recyclerNodelist.isShown())
                {
                    updataEditModeByCard(MYLIVE_MODE_CHECK);
                }

            }


        });
    }

    /**
     * 打开状态(卡片)
     */
    private void updataEditModeByCard(int state) {
        mEditModeCard=state;
        if (mEditModeCard == MYLIVE_MODE_EDIT) {
            cardCheckall.setVisibility(View.VISIBLE);
            editorStatusCard = true;
        } else {
            editorStatusCard = false;
            cardCheckall.setVisibility(View.GONE);
            isSelectAllCard=false;
        }
        node_adpter.setEditMode(state);
    }

    /***
     * 卡片的全选和反选
     */
    private void selectAllMainbycard() {
        if (node_adpter == null) return;
        if (!isSelectAllCard) {
            for (int i = 0, j = node_adpter.getNodeBeans().size(); i < j; i++) {
                node_adpter.getNodeBeans().get(i).setCheck(true);
            }
            index = node_adpter.getNodeBeans().size();
            checkboxAll.setText("取消全选");
            isSelectAllCard = true;
        } else {
            for (int i = 0, j = node_adpter.getNodeBeans().size(); i < j; i++) {
                node_adpter.getNodeBeans().get(i).setCheck(false);
            }
            index = 0;
            checkboxAll.setText("全选");
            isSelectAllCard = false;
        }
        node_adpter.notifyItemRangeChanged(0,listAdpter.getDatas().size());
    }

    /**
     * 全选和反选
     */
    private void selectAllMain() {
        if (listAdpter == null) return;
        if (!isSelectAll) {
            for (int i = 0, j = listAdpter.getDatas().size(); i < j; i++) {
                listAdpter.getDatas().get(i).setCheck(true);
            }
            index = listAdpter.getDatas().size();
            checkboxAll.setText("取消全选");
            isSelectAll = true;
        } else {
            for (int i = 0, j = listAdpter.getDatas().size(); i < j; i++) {
                listAdpter.getDatas().get(i).setCheck(false);
            }
            index = 0;
            checkboxAll.setText("全选");
            isSelectAll = false;
        }
        listAdpter.notifyItemRangeChanged(0,listAdpter.getDatas().size());
    }

    /**
     * 选择状态开启
     */
    private void updataEditMode() {
        mEditMode = mEditMode == MYLIVE_MODE_CHECK ? MYLIVE_MODE_EDIT : MYLIVE_MODE_CHECK;
        if (mEditMode == MYLIVE_MODE_EDIT) {
            cardCheckall.setVisibility(View.VISIBLE);
            editorStatus = true;
        } else {
            editorStatus = false;
            cardCheckall.setVisibility(View.GONE);
            clearAll();
            showselectbar=false;
        }
       listAdpter.setEditMode(mEditMode);
    }

    private void clearAll() {
        isSelectAll = false;

    }
    @Override
    protected void onResume() {
        super.onResume();
        beanDao = GreenDaoUtils.getInstance().getDaoSession().getNodeBeanDao();
        datas = getNodeByType(NodeBeanDao.Properties.Type.eq(type));
        configrecycler();
    }

    @Override
    protected void initdata() {
        //数据库去加载
        beanDao = GreenDaoUtils.getInstance().getDaoSession().getNodeBeanDao();
        type = getIntent().getExtras().getString("type");
        datas = getNodeByType(NodeBeanDao.Properties.Type.eq(type));

    }

    /**
     * 查询
     *
     * @param eq
     * @return
     */
    private List<NodeBean> getNodeByType(WhereCondition eq) {
        QueryBuilder<NodeBean> builder = beanDao.queryBuilder();
        builder.where(eq).build();
        return builder.list();
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_node;
    }



}
